#include "ds1302.h"
#include "INTRINS.H"
unsigned char gWRITE_RTC_ADDR[7] = {0x80,0x82,0x84,0x86,0x88,0x8a,0x8c};
unsigned char gREAD_RTC_ADDR[7] = {0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};
unsigned char gDS1302_TIME[7] = {0x47,0x51,0x13,0x03,0x07,0x06,0x21};


void ds1302_write_byte(unsigned char addr,unsigned char dat)
{
    unsigned char i= 0;
    ds1302_RST = 0;
    _nop_();
    ds1302_CLK = 0;
    _nop_();
    ds1302_RST = 1;
    _nop_();

    for ( i = 0; i < 8; i++)
    {
        ds1302_IO = addr&0x01;
        addr>>=1;
        ds1302_CLK = 1;
        _nop_();
        ds1302_CLK = 0;
        _nop_();
    }
        for ( i = 0; i < 8; i++)
    {
        ds1302_IO = dat&0x01;
        dat>>=1;
        ds1302_CLK = 1;
        _nop_();
        ds1302_CLK = 0;
        _nop_();
    }
    ds1302_RST= 0;
    _nop_9();
}

unsigned char  ds1302_read_byte(unsigned char addr)
{
    unsigned char i = 0;
    unsigned char temp = 0;
    unsigned char value = 0;
    ds1302_RST = 0;
    _nop_();
    ds1302_CLK;
    _nop_();
    ds1302_RST;
    _nop_();

    for ( i = 0; i < 8; i++)
        {
            ds1302_IO = addr&0x01;
            addr>>=1;
            ds1302_CLK = 1;
            _nop_();
            ds1302_CLK = 0;
            _nop_();
        }
    for ( i = 0; i < 8; i++)
    {
        temp = ds1302_IO;
        value = (temp<<7)|(value>>1);
        ds1302_CLK = 1;
        _nop_();
        ds1302_CLK = 0;
        _nop_();
    }
    ds1302_RST = 0;
    _nop_();
    ds1302_CLK = 1;
    _nop_();
    ds1302_IO = 0;
    _nop_();
    ds1302_IO = 1;
    return value;
}
void ds1302_init(void)
{
    unsigned char i = 0;
    ds1302_write_byte(0x8e,0x00);
    for ( i = 0; i < 8; i++)
    {
        ds1302_write_byte(gWRITE_RTC_ADDR[i],gDS1302_TIME[i]);
    }
    ds1302_write_byte(0x8e,0x80);
} 
void ds1302_read_time(void)
{
    unsigned char i = 0;
    for ( i = 0; i <8; i++)
    {
        ds1302_read_byte(gREAD_RTC_ADDR[i]);
    }
    
} 